package com.toolbox.service.impl;

import com.toolbox.service.DocumentService;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.hslf.usermodel.HSLFSlideShow;
import org.apache.poi.xslf.usermodel.XSLFSlideShow;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

@Service
public class DocumentServiceImpl implements DocumentService {

    private static final String TEMP_DIR = System.getProperty("java.io.tmpdir");

    @Override
    public InputStream convertDocument(MultipartFile file, String targetFormat) throws IOException {
        // 保存上传的文件到临时目录
        String originalFilename = file.getOriginalFilename();
        Path tempFilePath = Paths.get(TEMP_DIR, originalFilename);
        Files.write(tempFilePath, file.getBytes());

        // 根据源文件类型和目标格式执行转换
        Path convertedFilePath = convertFile(tempFilePath, targetFormat);

        // 返回转换后的文件输入流
        return new FileInputStream(convertedFilePath.toFile());
    }

    @Override
    public String getConvertedFilename(String originalFilename, String targetFormat) {
        int lastDotIndex = originalFilename.lastIndexOf(".");
        String baseName = lastDotIndex > 0 ? originalFilename.substring(0, lastDotIndex) : originalFilename;
        return baseName + "." + targetFormat.toLowerCase();
    }

    private Path convertFile(Path sourcePath, String targetFormat) throws IOException {
        String sourceFilename = sourcePath.getFileName().toString();
        String convertedFilename = getConvertedFilename(sourceFilename, targetFormat);
        Path convertedFilePath = Paths.get(TEMP_DIR, convertedFilename);

        // 这里应该根据实际需求实现各种文档格式的转换逻辑
        // 目前提供一个模拟实现
        try (InputStream in = new FileInputStream(sourcePath.toFile());
             OutputStream out = new FileOutputStream(convertedFilePath.toFile())) {
            
            // 模拟转换过程 - 实际项目中应该使用相应的库进行真正的转换
            byte[] buffer = new byte[4096];
            int bytesRead;
            while ((bytesRead = in.read(buffer)) != -1) {
                out.write(buffer, 0, bytesRead);
            }
        }

        return convertedFilePath;
    }

    // 清理临时文件的方法可以在实际项目中添加
    // private void cleanupTempFile(Path filePath) {
    //     try {
    //         Files.deleteIfExists(filePath);
    //     } catch (IOException e) {
    //         // 记录日志，不抛出异常
    //     }
    // }
}